package fnic.prehand.esagent.activity_measure;


import java.util.Map;

import org.apache.log4j.Logger;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.common.xcontent.json.JsonXContent;

import fnic.prehand.common.HttpMsgService;
import fnic.prehand.common.JacksonFormatService;
import fnic.prehand.common.ProbeAuthService;
import fnic.prehand.esagent.IndexAgent;


public abstract class CommonAgent extends IndexAgent{
	public static final JacksonFormatService jsonInstance = JacksonFormatService.getInstance();
	public static final HttpMsgService httpInstance = HttpMsgService.getInstance();
	private static final Logger logger = Logger.getLogger(CommonAgent.class);
	protected int probeType = 0;
	protected int probeId = 0;
	private final ProbeAuthService authInstance;
	private String failmsg;
	private final String ctrlURL;
	
	public CommonAgent(String idx, String type, String ctrlUrl, String skUrl) {
		super(idx, type);
		ctrlURL = ctrlUrl;
		authInstance = new ProbeAuthService(skUrl);
	}
	
	public void singleIndex(String source){
		String json = jsonAugment(source);
		IndexResponse response=null;
		try {
			response = client.prepareIndex(indexName, typeName)  
	            .setSource(json)  
	            .execute()  
	            .actionGet();
	    }catch(Exception e) {
			logger.error("Failed to process single index", e);
		}
		dealSingleIndexRsp(response);
	}
	
	/*
	 * redis接收数据 json格式解析
	 * sessionKey校验
	 */
	@Override
	protected String jsonAugment(Object item){
		Jsonmaps maps = new Jsonmaps();
		String[] jsonrecords = ((String)item).split("\\|", 2);
		if(jsonrecords.length != 2){
			logger.error("get redis record illegal, no josn|json");
			return null;
		}
		
		if(!parseHead(jsonrecords[0], maps)){
			//确保parse失败设置failmsg
			boolean phonefg = (probeType == 2 ? true:false);
			sendIdxResult(failmsg, phonefg);
			return null;
		}

		if(!parseBody(jsonrecords[1], maps)){
			//确保parse失败设置failmsg
			boolean phonefg = (probeType == 2 ? true:false);
			sendIdxResult(failmsg, phonefg);
			return null;
		}
		
		//将head里的内容追加到body里
		XContentHelper.update(maps.getBodymap(), maps.getHeadmap(),true);
		String json4index = jsonInstance.Obj2String(maps.getBodymap());
		return json4index;
	}
	
	protected boolean validSK(String sessionKey){
		if(!authInstance.validSessionKey(probeId, sessionKey)&&config.getSessionKeyFlg() != 0){
			return false;
		}
		return true;
	}
	/*
	 * 推送索引结果(探针)至管理节点
	 */
	public boolean sendIdxResult(String ctrlmsg, boolean isPhone) {
		StringBuilder rspbuilder = new StringBuilder();
		// boolean succeedFg = true;
		String url;
		if(!isPhone){
			url = ctrlURL+"/es/taskindex";
		}else{
			url = ctrlURL+"/es/mobileindexdesc";
		}
		boolean succeedFg = httpInstance.sendPostMsg(false, url, ctrlmsg, rspbuilder);
		// 推送数据至管理节点失败--推送索引消息至管理节点失败
		if (!succeedFg) {
			logger.error("notice ctrl fail, message:" + ctrlmsg);
		} else {
			logger.info("notice ctrl succeed, message:" + ctrlmsg);
		}

		return succeedFg;
	}
	

	
	public void setFailmsg(String failmsg) {
		this.failmsg = failmsg;
	}
	
	abstract boolean parseHead(String head, Jsonmaps maps);
	abstract boolean parseBody(String body, Jsonmaps maps);
	
	public class Jsonmaps{
		public Map<String, Object> getHeadmap() {
			return headmap;
		}
		public Map<String, Object> getBodymap() {
			return bodymap;
		}
		public void setHeadmap(Map<String, Object> headmap) {
			this.headmap = headmap;
		}
		public void setBodymap(Map<String, Object> bodymap) {
			this.bodymap = bodymap;
		}
		
		Map<String, Object> headmap;
		Map<String, Object> bodymap;
	}
	protected abstract void dealSingleIndexRsp(IndexResponse response);
}
